package com.example.demo.service.impl;

import com.example.demo.dto.ApprovalNoticeDto;
import com.example.demo.dto.PhoneNumberDto;
import com.alibaba.fastjson.JSONObject;
import com.example.demo.dto.WeChatLoginDto;
import com.example.demo.service.WxService;
import com.example.demo.utils.QRCodeUtil;
import com.example.demo.utils.WxUtils;
import com.example.demo.vo.WeChatLoginVo;
import com.fasterxml.jackson.databind.JsonNode;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Async;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.client.RestTemplate;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.security.AlgorithmParameters;
import java.security.Security;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class WxServiceImp implements WxService {
    private RestTemplate httpRest = new RestTemplate();
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.secret}")
    private String secret;
    /**
     * 根据车辆id打印二维码
     *
     * @return
     */
    @GetMapping("/getQRByCarId")
    @ApiOperation("根据id打印二维码")
    public void getQRByCarId(Integer carId, String carNo, HttpServletResponse response, HttpServletRequest request) throws IOException {
        ServletOutputStream stream = null;
        try {
            stream = response.getOutputStream();
//            String logoPath = "/file/logo.png";
//            String logoPath = ConvertTemplatePath.convertTemplatePath("/file/logo.png");
//            String logoPath = ResourceUtils.getFile("/file/logo.png").getPath();
            //使用工具类生成二维码

//            String code = request.getParameter("code");
            String url = "http://api.xinhuajian.com?id="+carId;
            QRCodeUtil.encode(url, "/file/logo.png", stream, true,carNo);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (stream != null) {
                stream.flush();
                stream.close();
            }

        }
    }

    /**
     * 微信登录
     *
     * @param code
     * @return
     */
    @Override
    public WeChatLoginVo weChatLogin(String code) throws Exception {
//        工程师 appid  wx5d3b0c5b6a6e82ae
//        工程师 secret  66308c5fd75ca3069e54db78644b4cfa
        //报修人 appid  wx58965288bfa5ad38
        //报修人 secret  eaa96c723fdf366ce55458ab3107f250
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx388be925758be1d1&secret=9fb1dedb6f80736cab3d68324b3bb125&js_code=" + code + "&grant_type=authorization_code";
        ResponseEntity<String> forObject = httpRest.getForEntity(url, String.class);
        WeChatLoginDto stu = (WeChatLoginDto) JSONObject.parseObject(forObject.getBody(), WeChatLoginDto.class);
        System.out.println("获取的id是"+stu.getUnionid());
        WeChatLoginVo vo = new WeChatLoginVo();
        vo.setRegister(Boolean.FALSE);
        vo.setOpenId(stu.getOpenid());
        vo.setUnionid(stu.getUnionid());
        vo.setSessionKey(stu.getSession_key());
        return vo;
    }

    /**
     * 获取手机号
     * @param phoneNumberDto
     * @return
     * @throws Exception
     */
    @Override
    public Object getPhoneNumber(PhoneNumberDto phoneNumberDto) throws Exception {
        // 被加密的数据
        byte[] dataByte = Base64.decode(phoneNumberDto.getEncryptedData());        // 加密秘钥
        byte[] keyByte = Base64.decode(phoneNumberDto.getSession_key());
        // 偏移量
        byte[] ivByte = Base64.decode(phoneNumberDto.getIv());
//        try {
        // 如果密钥不足16位，那么就补足.  这个if 中的内容很重要
        int base = 16;
        if (keyByte.length % base != 0) {
            int groups = keyByte.length / base + (keyByte.length % base != 0 ? 1 : 0);
            byte[] temp = new byte[groups * base];
            Arrays.fill(temp, (byte) 0);
            System.arraycopy(keyByte, 0, temp, 0, keyByte.length);
            keyByte = temp;
        }
        // 初始化
        Security.addProvider(new BouncyCastleProvider());
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        SecretKeySpec spec = new SecretKeySpec(keyByte, "AES");
        AlgorithmParameters parameters = AlgorithmParameters.getInstance("AES");
        parameters.init(new IvParameterSpec(ivByte));
        cipher.init(Cipher.DECRYPT_MODE, spec, parameters);// 初始化
        byte[] resultByte = cipher.doFinal(dataByte);
        if (null != resultByte && resultByte.length > 0) {
            String result = new String(resultByte, "UTF-8");
            JSONObject jsonObject = JSONObject.parseObject(result);
            String phoneNumber = (String) jsonObject.get("phoneNumber");
            UserExample example = new UserExample();
            example.createCriteria().andPhoneEqualTo(phoneNumber).andStatusEqualTo(StatusEnums.NO.getEcode());
            List<User> users = userMapper.selectByExample(example);
            if (users.size()>0){
                User user = users.get(0);
                user.setOpenId(phoneNumberDto.getOpenId());
                user.setUnionid(phoneNumberDto.getUnionid());
                String openId = getOpenId(phoneNumberDto.getOpenId());
                System.out.println(phoneNumber+"获取到的wxopenid是:"+openId);
                user.setWxOpenId(openId);
                userMapper.updateByPrimaryKeySelective(user);
            }else {
                throw new Exception("暂无登录权限 请联系管理员");
            }
            return JSONObject.parseObject(result);
        }

        return null;
    }

    /**
     * 微信模板消息推送
     *
     * @param approvalNoticeDto
     * @throws Exception
     */
    @Async
    public void sendNotice(ApprovalNoticeDto approvalNoticeDto) throws Exception {
        WxUtils.wxApproval(approvalNoticeDto);
    }

    /**
     * 微信公众号推送
     * @param approvalNoticeDto
     * @throws Exception
     */
    public void approvalNotice(ApprovalNoticeDto approvalNoticeDto) throws Exception {
        approvalNoticeDto.setOpenId(getOpenId(approvalNoticeDto.getOpenId()));
        String token = this.getOpenAccessToken();
        String	regUser = "http://wxdemo.xxxx.com/wxdevices/bodycompositionmain?openId="+approvalNoticeDto.getOpenId();
        String url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+token;
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("touser", approvalNoticeDto.getOpenId()); //推送用户openid
        map.put("template_id", "za4nMS73Zq8qxgpCUs_kMBWfAdR__lXXhCj-qUfQxEQ"); //指定模版ID
        map.put("appid", "wx5d3b0c5b6a6e82ae"); //指定模版ID
        Map<String, Object> data_map =new HashMap<String, Object>();
        Map<String, Object> first = new HashMap<String, Object>();
        first.put("value", "您有新的工单提醒");
        first.put("color", "#000000");
        //二维码名称A2
        Map<String, Object> keynote1 = new HashMap<String, Object>();
        keynote1.put("value", "A3");
        keynote1.put("color", "#000000");
        //报修时间
        Map<String, Object> keynote2 = new HashMap<String, Object>();
        keynote2.put("value", "2021-06-21 12:22:32");
        keynote2.put("color", "#000000");
        //报修客户名称
        Map<String, Object> keynote3 = new HashMap<String, Object>();
        keynote3.put("value", "张三");
        keynote3.put("color", "#000000");
        //联系方式
        Map<String, Object> keynote4 = new HashMap<String, Object>();
        keynote4.put("value", "132992912");
        keynote4.put("color", "#000000");
        //报修内容
        Map<String, Object> keynote5 = new HashMap<String, Object>();
        keynote5.put("value", "这是报修单的内容");
        keynote5.put("color", "#000000");
        //备注
        Map<String, Object> remark = new HashMap<String, Object>();
        remark.put("value", approvalNoticeDto.getRemark());
        remark.put("color", "#000000");
        data_map.put("first", first);
        data_map.put("keyword1", keynote1);
        data_map.put("keyword2", keynote2);
        data_map.put("keyword3", keynote3);
        data_map.put("keyword4", keynote4);
        data_map.put("remark", remark);
        map.put("data", data_map);
//            JSONObject json = JSONObject.fromObject(map);
        String json = JSONObject.toJSONString(map);
//            String result = HttpUtil.sendPost(url, json.toString());
        JsonNode ret = null;
        //发送post请求
        ret = Unirest.post(url).body(json).asJson().getBody();
//        System.out.println(ret);
    }

}
